<?php

namespace app\controllers;

use Yii;
use app\models\Article;
use app\models\Collect;
use app\controllers\BaseController;

class CollectController extends BaseController {

    public function actionIndex() {
        return $this->render('index');
    }

    public function actionAdd($aid) {
        if (Yii::$app->user->isGuest) {
            return json_encode(['error' => '请登录']);
        }

        //检查该问答是否存在
        $result = Article::findOne(['id' => $aid]);
        if ($result) {
            $collect = new Collect();
            $collect->uid = Yii::$app->user->identity->id;
            $collect->aid = $aid;
            $collect->save();
            return json_encode(['success' => '收藏成功']);
        }
    }

    public function actionCancel($aid) {
        if (Yii::$app->user->isGuest) {
            return json_encode(['error' => '请登录']);
        }

        //检查该问答是否存在
        $result = Article::findOne(['id' => $aid]);
        if ($result) {
            $collect = Collect::findOne(['uid' => Yii::$app->user->identity->id, 'aid' => $aid]);
            $collect->delete();
            return json_encode(['success' => '取消收藏成功']);
        }
    }

}
